<html>
    <head>
        <title>Join an existing game</title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
        <meta name = "viewport" content = "initial-scale = 1, user-scalable = no, width = 320">
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="apple-mobile-web-app-status-bar-style" content="black" />
        <link rel="stylesheet" href="/style.css" />
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    </head>
    <body>
        <style>
            p                { font-size:20px; }
            label            { font-size:20px; font-weight:bold; }

            select, input    { margin:5px 0 5px 0; font-size:20px; padding:5px; }
            select, input[type=text] { width:270px; }

            div#caption      { margin-top:20px; }
            div#caption h1  { position:relative; top:-10px; margin-left:10px; display:inline; }

            div#game_selection  { margin-top:10px; }
            div#game_selection label { display:block; }

            div#role_selection  { margin-top:10px; }
            div#role_selection p { font-size:20px; font-weight:bold; }
            div#role_selection label { margin-right:20px;  }

            div#player_name     { margin-top:10px; }
            div#player_name label { display:block; }

            div#btn_join        { margin-top:15px; }

        </style>
        <div id="frame_main">
            <div id="border_1">
                <div id="border_2">
                    <div id="caption">
                        <img src="/images/logo_pacman.png" title="logo"/>
                        <h1>Join an existing game</h1>
                    </div>

                    <div id="game_selection">
                        <label for="select_game">Select a Game:</label>
                        <select id="select_game" name="game">
                            <option value="-1">Searching for games...</option>
                        </select>
                    </div>

                    <div id="role_selection">
                        <p>Role:</p>
                        <input id="role_pacman" type="radio" name="role" value="0" checked />
                        <label for="role_pacman">PacMan</label>
                        <input id="role_ghost" type="radio" name="role" value="1"/>
                        <label for="role_ghost">Ghost</label>
                    </div>

                    <div id="player_name">
                        <label for="input_name">Player Name:</label>
                        <input id="input_name" type="text" name="name" value=""/>
                    </div>

                    <div id="btn_join" align="center">
                        <img src="/images/btn_join.png"/>
                    </div>
                <div id="info">
                </div>
                </div>
            </div>
        </div>
        <script type="text/javascript">
            var gamesArray = [];
            var state = 0;

            function getUrlVars()
            {
                var vars = [], hash;
                var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                for(var i = 0; i < hashes.length; i++)
                {
                    hash = hashes[i].split('=');
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
                return vars;
            }
            
            function game_join_done(data) {
                console.log('Joined game: ' + data);
                window.location.href='game.html?id=' + data.EntityId;
            }
            
            function join_game_error(XMLHttpRequest, textStatus, errorThrown) { 
                alert('Error trying to join the game'); 
            }
            
            function join_game_start(game_name, player_name, role) {
                $.ajax({
                    url: "http://tlvivi.co.il/JoinGame.ashx?jsoncallback=?", 
                    data: {"GameName": game_name, "PlayerName": player_name, "Role": role },
                    dataType: "jsonp",
                    jsonpString: "jsoncallback",
                    error: join_game_error,
                    success: game_join_done,
                });
            
                return false;
            }

            function join_game() {
                var game = parseInt($("select#select_game").val());
                if (game < 0) {
                    alert('No game selected');
                    return false;
                }
                game = gamesArray[game];

                var name = $("input#input_name").val();
                if (!name) {
                    alert('No name given');
                    return false;
                }

                var role = $("input[name='role']:checked").val();
                if (role < 0 || role > 1) {
                    alert('Invalid role selected');
                    return false;
                }

                console.log("pressed game: " + game.Name + " name: " + name + " role: " + role );

                join_game_start(game.Name, name, role);
            }   


            function init_game_error(XMLHttpRequest, textStatus, errorThrown) { 
                alert('Could not get games list');
            }

            function init_game(data) {
                var games_list = $("select#select_game");

                gamesArray = [];
                games_list.empty();

                $.each(data.Games, function(i,item) { 
                    item.players = item.Players.length;
                    games_list.append('<option value="' + i + '">' + item.Name + ' - ' + item.players + '</option>');
                    gamesArray.push(item);
                });

                /* If the user just created this game, make it auto-selected for him to join */ 
                selected_game = getUrlVars()["game_name"];
                if (selected_game) {
                    console.log('Specific game name requested: ' + selected_game);
                    $.each(gamesArray, function(i, item) {
                            if (item.Name == selected_game)
                                games_list.val(i);
                        });
                }
            }

            $(document).ready(function() {
                $("#info").ajaxError(function(event, request, settings){
                    $(this).html("<li>Error requesting page " + settings.url + "</li>");
                });
                    
                console.log("Start..");
                $("#btn_join").click(join_game);

                $.ajax({
                    url: "http://tlvivi.co.il/GetAllGames.ashx?jsoncallback=?", 
                    dataType: "jsonp",
                    jsonpString: "jsoncallback",
                    error: init_game_error,
                    success: init_game,
                });
            });
            </script>
    </body>
</html>
